package com.foo.common.base.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class FooUtils {
	private final static org.slf4j.Logger logger = org.slf4j.LoggerFactory
			.getLogger(FooUtils.class);

	public final static int ddl_pk_length = 36;// uuid2模式下，36是标准的id长度
	public final static String session_user_id = "uid";

	public static void main(String[] args) throws Exception {
		List<ImmutableMap<String, Object>> items = Lists.newArrayList();
		String result = FooUtils.generateDataWithMustache(ImmutableMap
				.<String, Object> of("isEmpty", false, "items", items),
				"alfred/script-input.xml");
		logger.info(result);

	}

	/**
	 * 
	 * @param scopes
	 *            用于模板的键值对，具体请参考Mustache文档
	 * @param template
	 *            以resources目录为根路径的模板地址，例如/myTmpl/myTmpl.jsp
	 * @return
	 * @throws Exception
	 */
	public static String generateDataWithMustache(Map<String, Object> scopes,
			String template) throws Exception {
		MustacheFactory mf = new DefaultMustacheFactory();
		Mustache mustache = mf.compile(template);
		Writer writer = new StringWriter();
		mustache.execute(writer, scopes);
		writer.flush();
		String result = writer.toString();
		return result;
	}

	public static void printJsonFromMap(HttpServletResponse response,
			Map<String, Object> myResultMap) {
		try {
			Gson gson = new GsonBuilder().disableHtmlEscaping().serializeNulls()
					.create();
			response.setCharacterEncoding(Charsets.UTF_8.toString());
			response.setContentType("text/plain");
			response.getWriter().write(gson.toJson(myResultMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void printSuccessJson(HttpServletResponse response) {
		Map<String, Object> myResultMap = Maps.newHashMap();
		myResultMap.put("ret", 0);
		myResultMap.put("msg", "");
		printJsonFromMap(response, myResultMap);
	}

	public static void printSuccessJson(HttpServletResponse response,
			Object myObject) {
		Map<String, Object> myResultMap = Maps.newHashMap();
		myResultMap.put("ret", 0);
		myResultMap.put("msg", myObject);
		printJsonFromMap(response, myResultMap);
	}

	public static String generateUUID() {
		return UUID.randomUUID().toString();
	}

}
